<?php
declare (strict_types=1);

namespace app\web\controller;

use app\BaseController;
use app\common\model\OfficialAccountModel;
use app\common\model\OfflineOrder;
use app\common\model\Shop;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use think\facade\Db;
use think\helper\Str;
use think\Validate;

class Index extends BaseController
{
    public $official = null;

    protected function initialize()
    {
        $shopId = input('shop_id', 0);
        $config = [
            'app_id' => 'wx593405606cc12cb5',
            'secret' => '08fd589a8314cf897cf919c9b72880f5',
            // ...
            'oauth'  => [
                'scopes'   => ['snsapi_base'],
                'callback' => "/web/oauthBack/shop_id/$shopId",
            ],
            // ..
        ];

        $this->official = Factory::officialAccount($config);
    }

    public function oauthBack()
    {
        try {
            $shopId = input('shop_id', 0);
            $code = $this->request->get('code');
            $user = $this->official->oauth->userFromCode($code);
            $user1 = $this->official->user->get($user->getId());
            if(isset($user1['unionid']) && $user1['unionid'] != ''){
                $unionid = $user1['unionid'];
            }else{
                $re = OfficialAccountModel::where('openid', $user1['openid'])->find();
                if($re){
                    $unionid = $re['unionid'];
                }else{
                    $unionid = $user1['openid'];
                }
            }
            $targetUrl = "/h5?shop_id={$shopId}&token={$unionid}";
            header('Location:' . $targetUrl); //
        } catch (\Exception $e) {
            exit($e->getMessage());
        }

    }

    public function oauth()
    {
        $oauth = $this->official->oauth;
        $redirectUrl = $oauth->redirect();
        header("Location: {$redirectUrl}");
        exit;

    }


    /**
     * 生成订单
     */
    public function createOrder()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
            'token'          => 'require',
            'number|金额'    => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shopId = $param['shop_id'];
        $payMoney = $param['number'];
        //根据商家信息获取发放积分比例
        $shop = Shop::where('id', $shopId)->find();
        if (!$shop->mchntCd || !$shop->shopId) {
            return error('当前商户未开通线下支付');
        }
        $points = round($payMoney * $shop->points_rate / 100);
        //生成订单号
        $orderNo = 'FO_' . msectime() . Str::random(3, 1);
        $order = OfflineOrder::create([
            'unionid'     => $param['token'],
            'shop_id'     => $shopId,
            'pay_money'   => $payMoney,
            'points'      => $points,
            'pay_status'  => 0,
            'send_status' => 0,
            'order_no'    => $orderNo,
            'pay_type'    => 1, //1:微信 2:支付宝
            'mchntCd'     => $shop->mchntCd
        ]);

        /**
         * 根据上传信息生成订单
         * 带上线上支付flag 和 积分发放标识
         * 并返回调起银行支付相关url
         * 和本地订单order_no
         * https://www.dingdangdui.com/index.php/web/order_notify
         */

        $url = "https://smsd.js96008.com/qrcsq/webservice/zhsd/pay";

        $data['mchntCd'] = $shop->mchntCd;
        $data['shopId'] = $shop->shopId;
        $data['transAmount'] = $payMoney;
        $data['channelType'] = 1;
        $data['traceNo'] = $orderNo;
        $data['notifyUrl'] = $this->request->domain() . '/index.php/web/order_notify';
        $data['nonceStr'] = Str::random(32);
        $data['returnUrl'] = $this->request->domain() . '/h5/pages/index/success';
        $sign = $this->sign($data, 'jsnxzhsdpay');
        $data['sign'] = $sign;

        $re = $url . '?';
        foreach ($data as $k => $v) {
            $re .= $k . '=' . $v . '&';
        }
        $re = rtrim($re, '&');
        return success($re);
        /**
         * 查询订单order_no银行订单信息
         * 并发放积分
         * 发放积分需要单独一个方法
         *
         * 还需要一个定时器专门处理 支付时间超过5分钟 但是没有更新订单状态的订单
         * 支付成功  支付失败  支付取消
         */
    }

    //签名
    public function sign($data, $key)
    {
        ksort($data);
        $str = '';
        foreach ($data as $k => $v) {
            if ($v) {
                $str .= $k . '=' . $v . '&';
            }
        }
        $str = $str . 'key=' . $key;
        return strtoupper(md5($str));
    }


    /**
     * 获取店铺详情
     */
    public function shopDetail()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }

        $shop = \app\common\model\Shop::field('id,logo,name')
            ->find($param['shop_id']);
        return success($shop);
    }

    /**
     * 订单信息回调
     * 订单支付完成 积分发放
     */
    public function orderNotify()
    {
        $param = $this->request->param();
        file_put_contents('test.txt', var_export($param, true), FILE_APPEND);
    }


    /**
     * 查询待支付的订单信息,并修改订单状态
     * 订单支付完成 积分发放
     * 定时任务
     */
    public function orderQuery()
    {
        $orderList = OfflineOrder::where('pay_status', 0)->order('id', 'desc')->limit(50)->select();

        foreach ($orderList as $order) {
            $re = $this->searchOrderInfo($order->mchntCd, $order->order_no);
            if ($re == 1 || $re == 2) {
                $order->pay_status = $re;
                $order->save();
            }
            if ($re == 3 && $order->create_time < time() - 60) {
                $order->pay_status = $re;
                $order->save();
            }
            if ($re == 4) {
                $order->pay_status = $re;
                $order->save();
            }
        }
        return $orderList->count();
    }

    /**
     * 查询 订单信息
     */
    public function searchOrderInfo($mchntCd, $orderNo)
    {
        $url = 'https://smsd.js96008.com/qrcsq/webservice/zhsd/queryOrderInfo?mchntCd=' . $mchntCd . '&traceNo=' . $orderNo;
        $re = file_get_contents($url);
        $re = json_decode($re, true);
        if ($re['respCode'] == '00') {
            switch ($re['transStatus']) {
                case '02':
                    return 1; //支付成功
                case '07':
                    return 2; // 支付取消
            }
        } elseif ($re['respCode'] == '01') {
            return 3;
        }
        return 4;
    }


}
